package com.qyhl.school.school.vlog.comment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.school.R;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.entity.school.SchoolVlogCommentBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import es.dmoral.toasty.Toasty;
import razerdp.basepopup.BasePopupWindow;

public class SchoolVlogCommentPopupWindow extends BasePopupWindow implements SchoolVlogCommentContract.SchoolVlogCommentView {
    private RecyclerView recyclerView;
    private LoadingLayout loadMask;
    private SmartRefreshLayout refreshLayout;
    private TextView sendBtn;
    private EditText content;
    private View popupView;
    private ImageView closeBtn;

    private CommonAdapter commonAdapter;

    List<SchoolVlogCommentBean> mDataList = new ArrayList<>();

    private Activity mContext;

    private int vlogId;

    private int lastId = 0;

    private String userName;

    private String mContent;

    private SchoolVlogCommentPresenter mPresenter;

    public SchoolVlogCommentPopupWindow(Activity context, int id) {
        super(context);
        mPresenter = new SchoolVlogCommentPresenter(this);
        vlogId = id;
        mContext = context;
        bindEvent();
        initView();
        setListener();
    }

    @Override
    protected Animation initShowAnimation() {
        return getDefaultScaleAnimation();
    }

    @Override
    public View getClickToDismissView() {
        return popupView.findViewById(R.id.close_btn);
    }

    @SuppressLint("InflateParams")
    @Override
    public View onCreatePopupView() {
        return popupView = LayoutInflater.from(getContext()).inflate(R.layout.popup_school_vlog_comment, null);
    }

    @Override
    public View initAnimaView() {
        return findViewById(R.id.popup_anima);
    }

    private void bindEvent() {
        recyclerView = popupView.findViewById(R.id.recycle_view);
        loadMask = popupView.findViewById(R.id.load_mask);
        refreshLayout = popupView.findViewById(R.id.refresh);
        sendBtn = popupView.findViewById(R.id.send_btn);
        content = popupView.findViewById(R.id.content);
        closeBtn = popupView.findViewById(R.id.close_btn);
    }

    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);

        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setRefreshHeader(new MaterialHeader(mContext));
        refreshLayout.setRefreshFooter(new ClassicsFooter(mContext));

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        recyclerView.setAdapter(commonAdapter = new CommonAdapter<SchoolVlogCommentBean>(mContext, R.layout.item_school_vlog_comment, mDataList) {
            @Override
            protected void convert(ViewHolder holder, SchoolVlogCommentBean bean, int position) {
                holder.setText(R.id.nickName, bean.getUser().getNickName());
                holder.setText(R.id.content, bean.getContent());
                holder.setText(R.id.date, DateUtils.mTranslateDate(bean.getCreateTime()));

                RoundedImageView headIcon = holder.getView(R.id.head_icon);
                Glide.with(mContext)
                        .load(bean.getUser().getLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).error(R.drawable.comment_head_default))
                        .into(headIcon);

                RecyclerView replyRecycler = holder.getView(R.id.reply_recycler);

                if (bean.getReplyList() != null && bean.getReplyList().size() > 0) {
                    replyRecycler.setVisibility(View.VISIBLE);
                    replyRecycler.setLayoutManager(new LinearLayoutManager(mContext));
                    replyRecycler.setAdapter(new CommonAdapter<SchoolVlogCommentBean.Reply>(mContext, R.layout.item_school_vlog_comment_reply, bean.getReplyList()) {
                        @Override
                        protected void convert(ViewHolder holder, SchoolVlogCommentBean.Reply reply, int position) {
                            holder.setText(R.id.reply_content, reply.getContent());

                            holder.setText(R.id.reply_date, reply.getCreateTime());
                        }
                    });
                } else {
                    replyRecycler.setVisibility(View.GONE);
                }
            }
        });

        mPresenter.getCommentList(vlogId, lastId);
    }

    private void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                lastId = 0;
                mPresenter.getCommentList(vlogId, lastId);
            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                lastId = 0;
                mPresenter.getCommentList(vlogId, lastId);
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getCommentList(vlogId, lastId);
            }
        });

        closeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideKeyboard(mContext, content);
                dismiss();
            }
        });

        content.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {//按下搜索
                    if (StringUtils.isNotEmpty(content.getText().toString()) && StringUtils.isNotEmpty(content.getText().toString().trim())) {

                        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                            @Override
                            public void login(boolean isLogin) {
                                if (isLogin) {
                                    userName = CommonUtils.getInstance().getUserName();
                                    mContent = content.getText().toString();
                                    mPresenter.sendComment(userName, mContent, vlogId);
                                } else {
                                    sendBtn.setEnabled(true);
                                    Toasty.normal(mContext, "尚未登录或登录已失效！").show();
                                    RouterManager.routerLogin(mContext, 0);
                                }
                            }

                            @Override
                            public void error(String s) {

                            }
                        });
                    } else {
                        sendBtn.setEnabled(true);
                        Toast.makeText(mContext, "评论内容不能为空！", Toast.LENGTH_SHORT).show();
                    }

                }
                return false;
            }
        });

        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBtn.setEnabled(false);
                if (StringUtils.isNotEmpty(content.getText().toString()) && StringUtils.isNotEmpty(content.getText().toString().trim())) {
                   CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                       @Override
                       public void login(boolean isLogin) {
                           if (isLogin) {
                               userName = CommonUtils.getInstance().getUserName();
                               mContent = content.getText().toString();
                               mPresenter.sendComment(userName, mContent, vlogId);
                           } else {
                               sendBtn.setEnabled(true);
                               Toasty.normal(mContext, "尚未登录或登录已失效！").show();
                               RouterManager.routerLogin(mContext, 0);
                           }
                       }

                       @Override
                       public void error(String s) {

                       }
                   });
                } else {
                    sendBtn.setEnabled(true);
                    Toast.makeText(mContext, "评论内容不能为空！", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 隐藏软键盘
     *
     * @param context 上下文对象
     * @param view    可弹出软键盘控件
     */
    public void hideKeyboard(Context context, View view) {
        if (view == null) return;
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void onDismiss() {
        super.onDismiss();
        hideKeyboard(mContext, content);
    }

    @Override
    public void setCommentList(List<SchoolVlogCommentBean> beanList, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setStatus(LoadingLayout.Success);
        lastId = beanList.get(beanList.size() - 1).getId();
        if (isMore) {
            refreshLayout.finishLoadMore();
        } else {
            refreshLayout.finishRefresh();
            mDataList.clear();
        }
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setError(String msg, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refreshLayout.finishLoadMore();
        } else {
            refreshLayout.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setErrorText(msg);
            loadMask.setErrorImage(R.drawable.empty_comment);
        }
    }

    @Override
    public void sendSuccess(boolean needVerify) {
        sendBtn.setEnabled(true);
        loadMask.setStatus(LoadingLayout.Success);

        if (needVerify) {
            Toast.makeText(mContext, "评论成功，等待审核！", Toast.LENGTH_SHORT).show();
        } else {
            lastId = 0;
            mPresenter.getCommentList(vlogId, lastId);
        }


        content.setText("");
        mContent = "";
        content.clearFocus();
        hideKeyboard(mContext, content);
    }

    @Override
    public void sendError(String msg) {
        sendBtn.setEnabled(true);
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
    }
}
